package com.mvp.shq.washer.view.widget;


import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import java.lang.reflect.Field;

public class MylViewPager extends ViewPager {
    public static final int DEFAULT_INTERVAL = 1500;

    public static final int LEFT = 0;
    public static final int RIGHT = 1;

    /**
     * 什么也不做,当滑动在最后一项或者第一项，什么也不做
     **/
    public static final int SLIDE_BORDER_MODE_NONE = 0;
    /**
     * 当滑动在最后一项或者第一项，开启循环，这种模式下，当滑到最后一个Item回到第一个Item，
     * 这种模式下，最后一个Item和第一个Item相同的话会显得自然一些
     **/
    public static final int SLIDE_BORDER_MODE_CYCLE = 1;
    /**
     * 当滑动在最后一项或者第一项，开启循环，并且阻止事件拦截
     **/
    public static final int SLIDE_BORDER_MODE_TO_PARENT = 2;

    /**
     * 自动滚动的时间,以毫秒为单位
     **/
    private long interval = DEFAULT_INTERVAL;
    /**
     * 自动滚动方向, default is {@link #RIGHT}
     **/
    private int direction = RIGHT;
    /**
     * 是否自动循环
     **/
    private boolean isCycle = true;
    /**
     * 接触时是否停止自动滚动
     **/
    private boolean stopScrollWhenTouch = true;
    /**
     * 如何处理当滑动在最后还是第一项
     **/
    private int slideBorderMode = SLIDE_BORDER_MODE_NONE;
    /**
     * 动画时是否自动滚动在最后或第一项取消动画
     **/
    private boolean isBorderAnimation = false;

    private Handler handler;
    private boolean isAutoScroll = false;
    private boolean isStopByTouch = false;
    private float touchX = 0f, downX = 0f;
    private CustomDurationScroller scroller = null;

    public static final int SCROLL_WHAT = 0;

    public MylViewPager(Context paramContext) {
        super(paramContext);
        init();
    }

    public MylViewPager(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        init();
    }

    private void init() {
        handler = new MyHandler();
        setViewPagerScroller();
    }

    public void setSlideBorderMode(int slideBorderMode) {
        this.slideBorderMode = slideBorderMode;
    }

    public void setDirection(int direction) {
        this.direction = direction;
    }

    /**
     * 启动动画
     */
    public void startAutoScroll() {
        isAutoScroll = true;
        sendScrollMessage(interval);
    }

    /**
     * 启动动画
     */
    public void startAutoScroll(int delayTimeInMills) {
        isAutoScroll = true;
        sendScrollMessage(delayTimeInMills);
    }

    /**
     * 停止动画
     */
    public void stopAutoScroll() {
        isAutoScroll = false;
        handler.removeMessages(SCROLL_WHAT);
    }


    /**
     * 设置动画切换的时间
     */
    public void setScrollDurationFactor(double scrollFactor) {
        scroller.setScrollDurationFactor(scrollFactor);
    }


    private void sendScrollMessage(long delayTimeInMills) {
        handler.removeMessages(SCROLL_WHAT);
        handler.sendEmptyMessageDelayed(SCROLL_WHAT, delayTimeInMills);
    }

    /**
     * 利用反射机制修改滚动的时间
     */
    private void setViewPagerScroller() {
        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            //插值器
            Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
            interpolatorField.setAccessible(true);

            scroller = new CustomDurationScroller(getContext(), (Interpolator) interpolatorField.get(null));
            scrollerField.set(this, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 选择滑动到哪一页
     */
    public void scrollOnce() {
        PagerAdapter adapter = getAdapter();
        int currentItem = getCurrentItem();
        int totalCount;
        if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
            return;
        }

        int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
        if (nextItem < 0) {
            if (isCycle) {
                setCurrentItem(totalCount - 1, isBorderAnimation);
                //如果是第一个就0延迟
                sendScrollMessage(0);
            }
        } else if (nextItem == totalCount) {
            if (isCycle) {
                setCurrentItem(0, isBorderAnimation);
                //如果是最后一个就0延迟
                sendScrollMessage(0);
            }
        } else {
            //默认情况就按照设定的时间切换图片
            setCurrentItem(nextItem, true);
            sendScrollMessage(interval);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (stopScrollWhenTouch) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN && isAutoScroll) {
                isStopByTouch = true;
                stopAutoScroll();
            } else if (ev.getAction() == MotionEvent.ACTION_UP && isStopByTouch) {
                startAutoScroll();
            }
        }

        if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT || slideBorderMode == SLIDE_BORDER_MODE_CYCLE) {
            touchX = ev.getX();
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                downX = touchX;
            }
            int currentItem = getCurrentItem();
            PagerAdapter adapter = getAdapter();
            int pageCount = adapter == null ? 0 : adapter.getCount();
            if ((currentItem == 0 && downX <= touchX) || (currentItem == pageCount - 1 && downX >= touchX)) {
                //事件拦截
                if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    if (pageCount > 1) {
                        setCurrentItem(pageCount - currentItem - 1, isBorderAnimation);
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onTouchEvent(ev);
            }
        }
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.onTouchEvent(ev);
    }


    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case SCROLL_WHAT:
                    scrollOnce();
                    //下面的方法，Handler向自身发送延迟消息
                    //sendScrollMessage(interval);
                default:
                    break;
            }
        }
    }

    class CustomDurationScroller extends Scroller {
        private double scrollFactor = 1;

        public CustomDurationScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        /**
         * 设置滚动切换的时间
         */
        public void setScrollDurationFactor(double scrollFactor) {
            this.scrollFactor = scrollFactor;
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, (int) (duration * scrollFactor));
        }
    }
}
